package com.shurdroides.sintesi;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import com.google.android.c2dm.server.C2DMessaging;
import com.google.android.c2dm.server.DeviceInfo;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

/**
 * Accion que se ejecuta cuando un usuario coge un objeto del mapa
 * @author alumneT
 *
 */
public class ActionCogerObjeto  extends Action {
	private static final Logger log = Logger.getLogger(ActionEnviaMensaje.class.getName());
	private Region region;
	private int idElemento;
	
	public ActionCogerObjeto (HttpServletRequest req, EntityManager em, PersistenceManager pm, Region reg, C2DMessaging push){
		setEntityManager(em);
		setPersistenceManager(pm);
		setCorreoUsuario(req.getParameter("correoUsu"));
		setIdElemento(Integer.parseInt(req.getParameter("id")));
		setPush(push);
	}
	@Override
	public boolean executeAction(Region reg) throws IOException {
		log.warning(""+getIdElemento());
		log.warning(""+reg.getObjetos().get(0).getNombre());
		reg.getObjetos().remove(getIdElemento());
		Iterator<Usuario> it = reg.getUsuariosPorCorreo().values().iterator();
		while (it.hasNext()) {
			Usuario us =it.next();
			 Key k = KeyFactory.createKey(DeviceInfo.class.getSimpleName(), us.getEmail());
			 DeviceInfo device = pm.getObjectById(DeviceInfo.class, k);
			 if(device.getDeviceRegistrationID()!=getCorreoUsuario()){
				 getPush().sendNoRetry(device.getDeviceRegistrationID(), "collapse", "action", "-1", "cadena", "libre");
			 }
		}
		return true;
	}

	public Region getRegion() {
		return region;
	}

	public void setRegion(Region region) {
		this.region = region;
	}
	public int getIdElemento() {
		return idElemento;
	}
	public void setIdElemento(int idElemento) {
		this.idElemento = idElemento;
	}

}
